package __goroutines

import (
	"fmt"
	"time"
)

func timeout() {
	fmt.Println("timeout start ...")
	c1 := make(chan string, 1)
	go func() {
		time.Sleep(2 * time.Second)
		c1 <- "result 1"
	}()
	select {
	case res := <-c1:
		fmt.Println(res)
	case <-time.After(1 * time.Second):
		// 一秒后退出等待
		fmt.Println("timeout 1")
	}

	c2 := make(chan string, 1)
	go func() {
		time.Sleep(2 * time.Second)
		c2 <- "result 2"
	}()
	select {
	case res := <-c2:
		fmt.Println(res)
	case <-time.After(3 * time.Second):
		fmt.Println("timeout 2")
	}
}

// 倒计时
func countDown() {
	c := make(chan int, 5)
	go func() {
		countDown := 5
		for i := 0; i < countDown; i++ {
			time.Sleep(time.Second)
			c <- i
		}
		close(c) // 一般不用关闭，close 用于显式退出range循环
	}()

	// 关闭channel后会跳出循环
	//for i := range c {
	//	fmt.Println("i=", i)
	//}

	//x := <- c
	//fmt.Println(x)

	// 关闭channel不会跳出循环
	// 一直读取零值
	for {
		select {
		case x := <-c:
			fmt.Println(x)
		}

	}
}

func bChan() {
	c := make(chan int, 2)
	go func() {
		time.Sleep(time.Second * 3)
	}()
	c <- 1
	fmt.Println("send 1")
	c <- 2
	fmt.Println("send 2")
	// 只会打印 send 1 和 send 2
	// 发送第三个就会阻塞住
	c <- 3
	fmt.Println("send 3")
	c <- 4
	fmt.Println("send 4")
}
